package com.naiterui.ehp.bs.ds.modules.statistics.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Preconditions;
import com.naiterui.ehp.bp.security.utils.SecurityUtils;
import com.naiterui.ehp.bs.ds.common.utils.DateUtils;
import com.naiterui.ehp.bs.ds.common.utils.JwtUser;
import com.naiterui.ehp.bs.ds.common.utils.PageVO;
import com.naiterui.ehp.bs.ds.common.vo.PageParamsVO;
import com.naiterui.ehp.bs.ds.modules.statistics.mapper.OrderStatisticsMapper;
import com.naiterui.ehp.bs.ds.modules.statistics.service.IOrderStatisticsService;
import com.naiterui.ehp.bs.ds.modules.statistics.vo.OrderStatisticsExcelVO;
import com.naiterui.ehp.bs.ds.modules.statistics.vo.OrderStatisticsVO;
import com.naiterui.ehp.bs.ds.modules.statistics.vo.SaleStatisticsParamVO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

/**
 * @author guoyongxiang
 * @date 2019/10/11 11:52
 * @since 1.0.0
 */
@Service
@AllArgsConstructor
public class OrderStatisticsServiceImpl implements IOrderStatisticsService {

    private final OrderStatisticsMapper orderStatisticsMapper;

    @Override
    public PageVO<OrderStatisticsVO> queryPage(PageParamsVO pageParamsVO, SaleStatisticsParamVO sale) {
        QueryWrapper<SaleStatisticsParamVO> entityWrapper = this.getEntityWrapper(pageParamsVO, sale);
        Page<OrderStatisticsVO> page = this.orderStatisticsMapper.getPage(pageParamsVO.getPage(), entityWrapper);
        return PageVO.toPageVo(page);
    }

    @Override
    public byte[] export(PageParamsVO pageParamsVO, SaleStatisticsParamVO sale) throws IOException {
        QueryWrapper<SaleStatisticsParamVO> entityWrapper = this.getEntityWrapper(pageParamsVO, sale);
        List<OrderStatisticsVO> list = this.orderStatisticsMapper.export(entityWrapper);

        List<OrderStatisticsExcelVO> excelVOList = new ArrayList<>();
        for (OrderStatisticsVO order : list) {
            OrderStatisticsExcelVO excelVO = new OrderStatisticsExcelVO();
            excelVO.setOrderSn(order.getOrderSn());
            Double totalAmount = BigDecimal.valueOf(order.getTotalAmount()).divide(BigDecimal.valueOf(100)).doubleValue();
            excelVO.setTotalAmount(totalAmount);
            excelVO.setCreatedAt(order.getCreatedAt());
            excelVO.setSendTime(order.getSendTime());
            excelVO.setExpressName(order.getExpressName());
            excelVO.setExpressCode(order.getExpressCode());
            excelVO.setOrderStatus(order.getOrderStatus());
            excelVOList.add(excelVO);
        }

        ExportParams exportParams = new ExportParams();
        ByteArrayOutputStream byteArrayOutputStream;
        try (Workbook workbook = ExcelExportUtil.exportExcel(exportParams, OrderStatisticsExcelVO.class, excelVOList)) {
            byteArrayOutputStream = new ByteArrayOutputStream();
            workbook.write(byteArrayOutputStream);
        }
        return byteArrayOutputStream.toByteArray();
    }

    private QueryWrapper<SaleStatisticsParamVO> getEntityWrapper(PageParamsVO pageParamsVO, SaleStatisticsParamVO sale) {
        QueryWrapper<SaleStatisticsParamVO> entityWrapper = pageParamsVO.getEntityWrapper("o");
        JwtUser currentUser = SecurityUtils.getCurrentUser();
        Long warehouseId = currentUser.getWarehouseId();
        Preconditions.checkNotNull(warehouseId, "仓库ID不能为null");

        entityWrapper.eq("o.warehouse_id", warehouseId);

        String orderSn = sale.getOrderSn();
        if (StringUtils.isNotBlank(orderSn)) {
            entityWrapper.in("o.order_sn", orderSn.split("\n"));
        }

        String skuNumber = sale.getSkuNumber();
        if (StringUtils.isNotBlank(skuNumber)) {
            entityWrapper.in("ps.number", skuNumber.split("\n"));
        }

        //发货日期
        String sendTimeGte = sale.getSendTimeGte();
        String sendTimeLte = sale.getSendTimeLte();
        entityWrapper.ge(StringUtils.isNotBlank(sendTimeGte), "o.send_time", sendTimeGte);
        entityWrapper.orderByDesc("created_at");
        if (StringUtils.isNotBlank(sendTimeLte)) {
            if (DateUtils.isNow(sendTimeLte)) {
                Date plus = DateUtils.plus(DateUtils.parseStrToDate(sendTimeLte), 1, ChronoUnit.DAYS);
                entityWrapper.le("o.send_time", plus);
            } else {
                entityWrapper.le("o.send_time", sendTimeLte);
            }
        }
        return entityWrapper;
    }
}
